package com.pig4cloud.pig.chatutils.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.pig.chatutils.entity.ChatMessageEntity;
import com.pig4cloud.pig.chatutils.service.ChatMessageService;

import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import com.pig4cloud.pig.common.security.annotation.HasPermission;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 聊天消息表
 *
 * @author pig
 * @date 2025-05-14 20:07:28
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/chatutils" )
@Tag(description = "chatutils" , name = "聊天消息表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ChatMessageController {

    private final ChatMessageService chatMessageService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param chatMessage 聊天消息表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @HasPermission("chatutils_chatutils_view")
    public R getChatMessagePage(@ParameterObject Page page, @ParameterObject ChatMessageEntity chatMessage) {
        LambdaQueryWrapper<ChatMessageEntity> wrapper = Wrappers.lambdaQuery();
        return R.ok(chatMessageService.page(page, wrapper));
    }


    /**
     * 通过条件查询聊天消息表
     * @param chatMessage 查询条件
     * @return R  对象列表
     */
    @Operation(summary = "通过条件查询" , description = "通过条件查询对象" )
    @GetMapping("/details" )
    @HasPermission("chatutils_chatutils_view")
    public R getDetails(@ParameterObject ChatMessageEntity chatMessage) {
        return R.ok(chatMessageService.list(Wrappers.query(chatMessage)));
    }

    /**
     * 新增聊天消息表
     * @param chatMessage 聊天消息表
     * @return R
     */
    @Operation(summary = "新增聊天消息表" , description = "新增聊天消息表" )
    @SysLog("新增聊天消息表" )
    @PostMapping
    @HasPermission("chatutils_chatutils_add")
    public R save(@RequestBody ChatMessageEntity chatMessage) {
        return R.ok(chatMessageService.save(chatMessage));
    }

    /**
     * 修改聊天消息表
     * @param chatMessage 聊天消息表
     * @return R
     */
    @Operation(summary = "修改聊天消息表" , description = "修改聊天消息表" )
    @SysLog("修改聊天消息表" )
    @PutMapping
    @HasPermission("chatutils_chatutils_edit")
    public R updateById(@RequestBody ChatMessageEntity chatMessage) {
        return R.ok(chatMessageService.updateById(chatMessage));
    }

    /**
     * 通过id删除聊天消息表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除聊天消息表" , description = "通过id删除聊天消息表" )
    @SysLog("通过id删除聊天消息表" )
    @DeleteMapping
    @HasPermission("chatutils_chatutils_del")
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(chatMessageService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param chatMessage 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @HasPermission("chatutils_chatutils_export")
    public List<ChatMessageEntity> exportExcel(ChatMessageEntity chatMessage,Long[] ids) {
        return chatMessageService.list(Wrappers.lambdaQuery(chatMessage).in(ArrayUtil.isNotEmpty(ids), ChatMessageEntity::getId, ids));
    }

    /**
     * 导入excel 表
     * @param chatMessageList 对象实体列表
     * @param bindingResult 错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @HasPermission("chatutils_chatutils_export")
    public R importExcel(@RequestExcel List<ChatMessageEntity> chatMessageList, BindingResult bindingResult) {
        return R.ok(chatMessageService.saveBatch(chatMessageList));
    }

    /**
     * 获取未读消息数量
     * @param userId 用户ID
     * @return R 未读消息数量
     */
    @Operation(summary = "获取未读消息数量", description = "获取指定用户的未读消息数量")
    @GetMapping("/unread/count")
    public R getUnreadCount(@RequestParam("userId") Long userId) {
        LambdaQueryWrapper<ChatMessageEntity> wrapper = Wrappers.<ChatMessageEntity>lambdaQuery()
                .eq(ChatMessageEntity::getReceiverId, userId)
                .eq(ChatMessageEntity::getIsRead, 0);
        return R.ok(chatMessageService.count(wrapper));
    }

    /**
     * 标记消息为已读
     * @param senderId 发送者ID
     * @param receiverId 接收者ID
     * @return R
     */
    @Operation(summary = "标记消息为已读", description = "标记指定发送者发给接收者的所有消息为已读")
    @PutMapping("/read")
    public R markAsRead(@RequestParam("senderId") Long senderId, @RequestParam("receiverId") Long receiverId) {
        LambdaQueryWrapper<ChatMessageEntity> wrapper = Wrappers.<ChatMessageEntity>lambdaQuery()
                .eq(ChatMessageEntity::getSenderId, senderId)
                .eq(ChatMessageEntity::getReceiverId, receiverId)
                .eq(ChatMessageEntity::getIsRead, 0);
        
        ChatMessageEntity updateEntity = new ChatMessageEntity();
        updateEntity.setIsRead(1);
        
        return R.ok(chatMessageService.update(updateEntity, wrapper));
    }

    /**
     * 获取聊天历史记录
     * @param userId1 用户1ID
     * @param userId2 用户2ID
     * @return R 聊天历史记录
     */
    @Operation(summary = "获取聊天历史记录", description = "获取两个用户之间的聊天历史记录")
    @GetMapping("/history")
    public R getChatHistory(@RequestParam("userId1") Long userId1, @RequestParam("userId2") Long userId2) {
        // 获取两个用户之间的所有消息
        LambdaQueryWrapper<ChatMessageEntity> wrapper = Wrappers.<ChatMessageEntity>lambdaQuery()
                .nested(w -> w
                        .eq(ChatMessageEntity::getSenderId, userId1)
                        .eq(ChatMessageEntity::getReceiverId, userId2)
                        .or()
                        .eq(ChatMessageEntity::getSenderId, userId2)
                        .eq(ChatMessageEntity::getReceiverId, userId1)
                )
                .orderByAsc(ChatMessageEntity::getCreateTime);
        
        return R.ok(chatMessageService.list(wrapper));
    }
}
